/**
 * rem 自动计算
 * 根据浏览器宽度对比最大宽度，得出百分值，并转化为像素写入 html.style.font-size
 * @param  {number} max = 750 最大宽度
 * @param  {number} min = 320 最小宽度
 * @return {() => void}       返回计算函数，默认调用一次
 */
export const autosize = (max = 750, min = 320) => {
  const htmlstyle: any = document.getElementsByTagName('html')[0].style;
  const resize = () => {
    const w: number = innerWidth;
    htmlstyle.fontSize = (((w > max && max) || (w < min && min) || w) / max) * 100 + 'px';
  };
  resize();
  return resize;
};

/**
 * 异步暂停
 */
export const sleep = (timeOut: number) => new Promise(resolve => setTimeout(resolve, timeOut));

/**
 * 获取范围内随机数
 */
export const randomInt = (min: number, max: number) => Math.floor(Math.random() * (max - min + 1)) + min;

/**
 * 清除所有空格
 */
export const trim = (str: string) => str.replace(/\s/g, '');

/**
 * json字符串 转 json对象
 */
export const jsonParse: (json: string, defaults?: any) => any = (json, defaults = []) => {
  try {
    return JSON.parse(json) || defaults;
  } catch (e) {
    return defaults;
  }
};

/**
 * json对象 转 json字符串
 */
export const jsonStringify = (data: object, defaults = '{}', space?: string | number) => {
  try {
    return JSON.stringify(data, null, space) || defaults;
  } catch (e) {
    return defaults;
  }
};
